//基地址
const baseURL = "https://pcapi-xiaotuxian-front-devtest.itheima.net"
import store from "@/store"
const request = {
  invoke(config) {
    //Loading效果
    uni.showLoading({
      title: "加载中...",
      mask: true,
    })
    //请求标头
    config.url = baseURL + config.url
    //请求超时
    config.timeout = 5000
    //请求头信息
    config.header = {
      ...config.header,
      "source-client": "miniapp",
    }
    // console.log(store)
    const token = store.state.user.userInfo.token
    if (token) {
      config.header.Authorization = `Bearer ${token}`
    }
    return config
  },
  complete() {
    //关闭Loading效果
    uni.hideLoading()
  },
}

uni.addInterceptor("request", request)
//上传文件
uni.addInterceptor("uploadFile", request)

const http = (config) => {
  return new Promise((resolve, reject) => {
    uni.request({
      ...config,
      success: (res) => {
        resolve(res)
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data)
        } else {
          uni.showToast({
            title: res.data.message || "系统出错，请稍后重试",
            icon: "none",
            duration: 2000,
          })
        }
        // console.log(res)
      },
      fail: (err) => {
        uni.showToast({
          title: "网络出错，请稍后重试",
          icon: "none",
          duration: 2000,
          mask: true,
        })
        reject(err)
      },
    })
  })
}
const methods = ["get", "post", "put", "delete"]
methods.forEach((method) => {
  http[method] = (url, data, config) => {
    return http({
      url,
      data,
      method,
      ...config,
    })
  }
})
export default http
